package com.buka.recipe.security.handler;

import com.alibaba.fastjson2.JSON;
import com.buka.recipe.common.result.ResultGenerator;
import com.buka.recipe.system.service.LoginLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author admin
 */
@Log4j2
@Component
public class JsonAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final LoginLogService loginLogService;

    @Autowired
    public JsonAuthenticationFailureHandler(LoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        // 保存日志
        loginLogService.save(request, false, exception.getMessage());
        log.info("登录失败, {}", exception.getMessage());

        response.setContentType("application/json;charset=utf-8");
        if (exception instanceof AccountExpiredException) {
            // 账号过期
            response.getWriter().write(JSON.toJSONString(ResultGenerator.genFailResult("账号过期")));
        } else if (exception instanceof BadCredentialsException) {
            // 密码错误
            response.getWriter().write(JSON.toJSONString(ResultGenerator.genFailResult("用户名或密码错误")));
        } else if (exception instanceof CredentialsExpiredException) {
            // 密码过期
            response.getWriter().write(JSON.toJSONString(ResultGenerator.genFailResult("密码过期")));
        } else if (exception instanceof DisabledException) {
            // 禁用账号
            response.getWriter().write(JSON.toJSONString(ResultGenerator.genFailResult("禁用账号")));
        } else if (exception instanceof LockedException) {
            // 锁定删号
            response.getWriter().write(JSON.toJSONString(ResultGenerator.genFailResult("锁定账号")));
        } else {
            // 其它登录错误
            response.getWriter().write(JSON.toJSONString(ResultGenerator.genFailResult(exception.getMessage())));
        }
    }

}
